package com.eliza.v.http.ftp


import com.eliza.v.http.VertxTools
import io.vertx.core.AbstractVerticle
import io.vertx.core.Promise
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.BodyHandler
import io.vertx.kotlin.core.dns.addressResolverOptionsOf

/*
 * @author <a href="http://tfox.org">Tim Fox</a>
 */

//ValidationExampleServer//验证示例服务器
class Upload : AbstractVerticle() {

    override fun start(startPromise: Promise<Void>?) {
        super.start(startPromise)
        uploadFile()
    }

    @Throws(Exception::class)
    private fun uploadFile() {
        val router = Router.router(vertx)
        // Enable multipart form data parsing
        var filesPath = "Upload.verify"
        router.route().handler(BodyHandler.create().setUploadsDirectory(filesPath))
        router.route("/Upload").handler { rc: RoutingContext ->
            rc.response().putHeader("content-type", "text/html").end(
                """<form action="/Upload/form" method="post" enctype="multipart/form-data">
                <div>
                    <label for="name">Select a file:</label>
                    <input type="file" name="file" />
                </div>
                <div class="button">
                    <button type="submit">Send</button>
                </div></form>"""
            )
        }

        // handle the form
        router.post("/Upload/form").handler { ctx: RoutingContext ->
            ctx.response().putHeader("Content-Type", "text/plain")
            ctx.response().isChunked = true
            for (f in ctx.fileUploads()) {
                println("/Upload/form files send AllReady")
                ctx.response().write("Filename: " + f.fileName())
                ctx.response().write("\n")
                ctx.response().write("Size: " + f.size() / 1024 / 1024)
            }
            ctx.response().end()
        }

        VertxTools.result(vertx, this, "uploadFile", router, 8080)
    }


}